﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections.ObjectModel;
using Microsoft.Phone.Tasks;
using System.Device.Location;
using System.Threading.Tasks;
using WP_Customer_ShopMob.GeocodeService;
using System.IO.IsolatedStorage;

namespace WP_Customer_ShopMob.Views
{
    public partial class ArticlesPage : PhoneApplicationPage
    {
        Model.Repository repo = new Model.Repository();
        GeoCoordinateWatcher location;
        GeocodeServiceClient geocodeService;
        GeocodeRequest geocodeReq = new GeocodeRequest();
        GeocodeLocation locations = new GeocodeLocation();
        GeoCoordinate geo = new GeoCoordinate();
        ViewModels.ArticleViewModel avm = new ViewModels.ArticleViewModel();
        ViewModels.PanierViewModel pvm;
        public ArticlesPage()
        {
            InitializeComponent();
            if ( location == null )
            {

            }
            location = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            location.Start();
            location.MovementThreshold = 30;
            geo = location.Position.Location;
            //On instancie le service
            geocodeReq.Credentials = new Credentials() { ApplicationId = "Ai1fgA62BvHepJJP47IuQ_KsxXbYgfPZRCH_vl3OI4YG9olsSn2mzshkD9lJUgUH" };
            location.PositionChanged += location_PositionChanged;
            location.StatusChanged += location_StatusChanged;
        }

        void location_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Disabled)
            {
                location.Stop();
                location.StatusChanged -= location_StatusChanged;
                location.PositionChanged -= location_PositionChanged;
                location = null;
            }
        }

        void location_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            getCurrentPosition(geo);
            updateLstMagasins();
            geocodeService.CloseAsync();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            string idArticle;
            NavigationContext.QueryString.TryGetValue("id", out idArticle);
            long id = long.Parse(idArticle);
            var articlesLoad = Helper.IsolatedStorage.Load<ObservableCollection<ViewModels.ArticleViewModel>>("articles");
            avm = articlesLoad.SingleOrDefault(x => x.IdArticle == id);
            if (!avm.IsDataLoaded)
            {
                avm.LoadData();
            }
            IsolatedStorageSettings.ApplicationSettings.TryGetValue("panier", out pvm);
            this.DataContext = avm;
        }

        private void updateLstMagasins()
        {
            foreach (var magasin in avm.ListMagasins)
            {

                //On instancie la requête
                geocodeReq.Query = magasin.ville;
                geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
                geocodeService.GeocodeAsync(geocodeReq);
                geocodeService.GeocodeCompleted += (s, eve) =>
                {
                    if (eve.Result != null && eve.Result.Results.Any(x => x.Locations != null && x.Locations.Any()))
                    {
                        locations = eve.Result.Results.FirstOrDefault().Locations.FirstOrDefault();
                        GeoCoordinate other = new GeoCoordinate(locations.Latitude, locations.Longitude);
                        magasin.distance = Math.Round(geo.GetDistanceTo(other) / 1000, 2);
                    }
                    else
                    {
                        MessageBox.Show("Impossible de localiser");
                    }
                    lst_magasin.ItemsSource = avm.ListMagasins.OrderBy(x => x.distance);
                };
            }
        }

        private void getCurrentPosition(GeoCoordinate geo)
        {
            ReverseGeocodeRequest rq = new ReverseGeocodeRequest();
            rq.Credentials = new Credentials() { ApplicationId = "Ai1fgA62BvHepJJP47IuQ_KsxXbYgfPZRCH_vl3OI4YG9olsSn2mzshkD9lJUgUH" };
            rq.Location = new Location() { Latitude = geo.Latitude, Longitude = geo.Longitude };
            geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            geocodeService.ReverseGeocodeAsync(rq);
            geocodeService.ReverseGeocodeCompleted += geocodeService_ReverseGeocodeCompleted;
        }

        void geocodeService_ReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                //MessageBox.Show("Je suis situé à "+e.Result.Results.FirstOrDefault().DisplayName);
            }
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (pvm != null)
            {
                pvm.ListArticles.Add(avm, sld_qte.Value);
                pvm.Save();
                MessageBox.Show("Ajout de " + sld_qte.Value.ToString() + " " + avm.Nom + " dans le panier");
            }
        }

        private void sld_qte_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (e.NewValue != e.OldValue)
            {
                sld_qte.Value = Math.Round(e.NewValue,0);
            }
        }
    }
}